package com.huaxiafinance.management.controller;

import com.huaxiafinance.management.dto.request.AddScoreResupplymentDto;
import com.huaxiafinance.management.dto.request.QueryScoreResupplymentDto;
import com.huaxiafinance.management.model.ScoreResupplyment;
import com.huaxiafinance.management.service.ScoreResupplymentService;
import com.huaxiafinance.management.util.MessageResult;
import com.huaxiafinance.management.util.ServiceCode;
import com.huaxiafinance.management.util.StringUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 积分补发记录查询接口
 */
@Controller("scoreResupplymentController")
@RequestMapping("/scoreResupply")
public class ScoreResupplymentController {

  private static final Logger logger = Logger.getLogger(ScoreResupplymentController.class);

  @Autowired
  private ScoreResupplymentService scoreResupplymentService;

  /**
   * 积分补发记录查询
   *
   * @return String
   */
  @RequestMapping(value = "/query", produces = "application/json; charset=utf-8")
  public @ResponseBody
  String query(@Valid @ModelAttribute("dto") QueryScoreResupplymentDto dto) {
    logger.info("查询积分补发记录的请求参数=============================>" + dto);
    MessageResult result = new MessageResult();
    if (dto.getStart() == null || dto.getEnd() == null) {
      result.setRows(0);
      result.setData(new ArrayList());
      result.setSuccessResult();
      return result.getAsJSON();
    }
    List<ScoreResupplyment> list = scoreResupplymentService.query(dto);
    int rows = scoreResupplymentService.selectCount(dto);
    result.setRows(rows);
    result.setSuccessResult();
    result.setData(list);
    logger.info("查询积分补发记录的响应结果=============================>" + result.getAsJSON());
    return result.getAsJSON();
  }

  @RequestMapping(value = "/add", produces = "application/json; charset=utf-8")
  public @ResponseBody
  String add(@Valid @RequestBody AddScoreResupplymentDto dto) {
    logger.info("添加积分补发的请求参数=============================>" + dto);
    MessageResult result = new MessageResult();
    try {
      result = scoreResupplymentService.insert(dto);
      return result.getAsJSON();
    } catch (Exception e) {
      result.setFailureResult(e.getMessage());
      e.printStackTrace();
    }
    logger.info("查询积分补发记录的响应结果=============================>" + result.getAsJSON());
    return result.getAsJSON();
  }

  /**
   * 通过excel(后缀为.xlsx)批量补发积分,前端用multipart/form-data提交
   */
  @RequestMapping(value = "/batchAdd", method = RequestMethod.POST, produces = "multipart/form-data;charset=utf-8")
  public @ResponseBody
  String batchAdd(HttpServletRequest request) {
    MessageResult result = new MessageResult();
    try {
      String comment = request.getParameter("comment");
      if (StringUtil.isNullOrEmpty(comment)) {
        result.setResultMessage(ServiceCode.PARAMETERS_ERROR);
        return result.getAsJSON();
      }
      Double score = Double.valueOf(request.getParameter("score"));
      if (StringUtil.isNullOrEmpty(score)) {
        result.setResultMessage(ServiceCode.PARAMETERS_ERROR);
        return result.getAsJSON();
      }
      Integer adminUserId = Integer.valueOf(request.getParameter("adminUserId"));
      if (StringUtil.isNullOrEmpty(adminUserId)) {
        result.setResultMessage(ServiceCode.PARAMETERS_ERROR);
        return result.getAsJSON();
      }
      Integer giveGrowthValue = Integer.valueOf(request.getParameter("giveGrowthValue"));
      if (StringUtil.isNullOrEmpty(giveGrowthValue)) {
        result.setResultMessage(ServiceCode.PARAMETERS_ERROR);
        return result.getAsJSON();
      }
      MultipartHttpServletRequest re = (MultipartHttpServletRequest) request;
      MultipartFile file = re.getFile("inputStream");
      CommonsMultipartFile cf = (CommonsMultipartFile) file;
      //获得输入流
      InputStream inputStream = cf.getInputStream();
      //文件名
      String fileName = file.getOriginalFilename();
      if (!fileName.endsWith(".xlsx")) {
        result.setResultMessage(ServiceCode.SCORE_FILE_UPLOAD_ERROR);
        return result.getAsJSON();
      }
      logger.info(
          "批量补发积分的请求参数=============================>" + "adminUserId:" + adminUserId + ",score:"
              + score + ",comment:" + comment + "," + inputStream);
      //创建一个积分补发的dto
      AddScoreResupplymentDto dto = new AddScoreResupplymentDto();
      dto.setFileName(fileName);
      dto.setComment(comment);
      dto.setScore(score);
      dto.setAdminUserid(adminUserId);
      dto.setGiveGrowthValue(giveGrowthValue);
      result = scoreResupplymentService.batchAdd(inputStream, dto);
    } catch (Exception e) {
      result.setFailureResult(e.getMessage());
      e.printStackTrace();
    }
    logger.info("批量补发积分的响应结果=============================>" + result.getAsJSON());
    return result.getAsJSON();
  }
}
